#ifndef LOOPER_H
#define LOOPER_H

#include <cstdint>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <memory>

namespace looper
{
	// 接口
	class IRunnable
	{
	public:
		virtual void run() = 0;
	};
	
	using RunnableSP = std::shared_ptr<IRunnable>;
	
	class Handler;
	
	// 循环器, 调度IRunnable
	class Looper
	{
		friend class Handler;
	public:
		Looper();
		~Looper();
		
	public:
		// 不要调用这个函数(框架自动调用)
		void loop();
		
	private:
		void postDelayed(Handler* handler, RunnableSP runnableSP, uint64_t delayMillis);
		void removeCallbacks(Handler* handler, RunnableSP runnableSP);
		
	private:		
		bool mIsLoop{true};
		std::thread mThread;
		std::mutex mMutex;
		std::condition_variable mCondVar;		
	};
	
	// 处理器, 发送或者移除IRunnable
	class Handler
	{
	public:
		Handler(Looper* looper);
		
		// Looper中此Handler发出的还没被执行的IRunnable会被清除
		~Handler();
		
		// (如果Looper已经销毁,此post失效)
		void post(RunnableSP runnableSP);
		
		// (如果Looper已经销毁,此post失效)
		void postDelayed(RunnableSP runnableSP, uint64_t delayMillis);
		
		// 清除所有此Handler发出去的还没被执行的IRunnable
		// r == nullptr, 移除所有该Handler发处的IRunnable
		void removeCallbacks(RunnableSP runnableSP);
		
	private:
		Looper* mLooper{nullptr};
	};
	
} // namespace looper

#endif